<template>
  <!-- <map
      id="map"
      :longitude="longitude"
      :latitude="latitude"
      :scale="scale"
      @regionchange="onRegionChange"
      @tap="onMapTap"
    >
      <cover-view v-if="polygonPoints.length" class="polygon-cover">
        已绘制地块
      </cover-view>
    </map> -->

  <view>
    <map
      :scale="scale"
      id="test_map"
      ref="map1"
      style="width: 100%; height: 600px"
      :show-location="true"
      :longitude="map.longitude"
      :latitude="map.latitude"
      :markers="markers"
      :polyline="polyline"
      show-compass="true"
      :polygons="polygons"
      :controls="controls"
      @tap="tapMap"
    >
      <cover-view v-if="funGeometryList.length" class="polygon-cover">
        已绘制地块
      </cover-view>
    </map>
    <view v-if="show">
      <button @click="area">绘制区域</button>
      <button @click="doDelete">清空</button>
      <button @click="back">返回</button>
    </view>
  </view>
</template>

<script>
import { baseMixins } from "@/mixins/baseMixins";
import { requestPost, requestGet } from "@/util/request";

export default {
  mixins: [baseMixins],
  props: {
    longitude: {
      type: Number,
      default: 111.752216,
    },
    latitude: {
      type: Number,
      default: 40.825271,
    },
    scale: {
      type: Number,
      default: 16,
    },
  },
  data() {
    return {
      polygonPoints: [],
      //   scale: 11,
      center: null,
      //   latitude: 0,
      //   longitude: 0,
      chitId: "",
      rings: [],
      funGeometryList: [],
      //绘制区域
      polygons: [],
      //区域点lsit
      option: [
        // {
        //   longitude: 115.52125,
        //   latitude: 39.794587,
        // },
      ],
      mapContext: {},
      map: {
        longitude: "111.752216", //经度
        latitude: "40.825271", //纬度
      },
      //线数据
      polyline: [],
      //点数据list
      pointList: [
        // {
        //   longitude: 115.52125,
        //   latitude: 39.794587,
        // },
      ],
      controls: [],
      //撒点list
      markers: [],
      isShow: "", // 只显示地块
      show: true,// 显示画地块按钮
    };
  },
  watch: {
    option: {
      handler(newValue, oldValue) {
        // 当option数组发生变化时，调用mutation来更新store中的状态
        this.$store.commit("setMapOptions", newValue);
      },
      deep: true, // 深度监听，因为option是一个数组
    },
    isShow: {
      handler(newValue, oldValue) {
        if (newValue == 1) {
          this.show = false;
        } else {
        }
      },
    },
  },
  mounted() {
    this.mapContext = uni.createMapContext("test_map", this);
  },
  methods: {
    back() {
      uni.navigateBack();
    },
    onMapTap(e) {
      console.log("e", e.detail);
      // 当点击地图时的处理函数
      if (this.polygonPoints.length >= 3) {
        // 至少需要3个点才能构成一个地块
        // uni.showToast({
        //   title: "至少需要3个点",
        //   icon: "none",
        // });
        // return;
      }
      // 添加点到地块坐标点数组
      this.polygonPoints.push([]);
      this.polygonPoints[0].push([
        e.detail.longitude
          ? e.detail.longitude
          : 111.752216 + Math.random() * 0.000001,
        e.detail.latitude
          ? e.detail.latitude
          : 40.825271 + Math.random() * 0.000001,
      ]);
      this.area();
      //   console.log(this.polygonPoints);
      this.$emit("onMapTap", this.polygonPoints);
    },
    tapMap(e) {
      var that = this;
      var id = e.currentTarget.id;
      var maps = uni.createMapContext("test_map", this).$getAppMap();

      maps.onclick = function (point) {
        console.log(point);

        let _point = {
          id: that.markers.length + 1, // 自动增加 id
          width: 4, //宽
          height: 4, //长
          latitude: point.latitude,
          longitude: point.longitude,
          iconPath: "/static/image/location.png",
          anchor: {
            x: 0, //图标锚点，默认图标中心点
            y: 0, // 图标锚点，默认图标中心点
          },
        };
        // point.iconPath = "/static/default.png";
        that.markers = that.markers.concat(_point);

        that.option.push({
          longitude: point.longitude,
          latitude: point.latitude,
        });
        uni.showToast({
          title: "添加成功",
          icon: "none",
        });
      };
    },
    //描点
    addPoint(latitude, longitude) {
      let point = {
        id: this.markers.length + 1, // 自动增加 id
        width: 40, //宽
        height: 40, //长
        latitude: latitude,
        longitude: longitude,
        // iconPath: "/static/default.png", // 使用默认定位图标
        // anchor: {
        //   x: 0.5,//图标锚点，默认图标中心点
        //   y: 1,// 图标锚点，默认图标中心点
        // },
      };
      this.markers.push(point);
    },
    //绘制区域
    area() {
      // 点线面，如果不是面就不让他生成
      if (this.option.length > 2) {
        this.polygons = [
          {
            strokeWidth: 1,
            strokeColor: "#67c23a",
            fillColor: "#1791fc66",
            dottedLine: false,
            arrowLine: false,
            level: "abovelabels",
            points: this.option,
          },
        ];
        this.polygons[0].points = [];
        this.polygons[0].points.push(...this.option);
      } else {
        uni.showModal({
          title: "至少选择三个点！",
          duration: 1000,
          icon: "error",
        });
      }
    },
    doDelete() {
      //清空区域
      (this.polygons = []),
        // 清空点
        (this.markers = []),
        (this.option = []),
        // 清空线
        (this.polyline = []);
    },
    //划线
    line() {
      // 更新 polyline 数组
      this.polyline = [
        {
          points: this.option,
          color: "#ff0f0f",
          width: 10,
          dottedLine: true,
          arrowLine: true,
          colorList: true,
        },
      ];
    },
  },
  created() {},
  onLoad(queryParams) {
    let that = this;
      // 首先检查并请求定位权限
      if (uni.authorize) {
        uni.authorize({
          scope: "scope.userLocation",
          success() {
            // 用户已授权，获取位置信息
            uni.getLocation({
              type: "wgs84",
              success: (res) => {
                that.map.latitude = parseFloat(res.latitude.toFixed(6));
                that.map.longitude = parseFloat(res.longitude.toFixed(6));
                console.log("获取地址成功", res);
              },
              fail: (error) => {
                console.error("获取位置失败：", error);
              },
            });
          },
          fail() {
            // 用户未授权，提示并引导去设置
            uni.showModal({
              title: "提示",
              content: "此功能需要获取您的地理位置，请确认授权",
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting();
                }
              },
            });
          },
        });
      } else {
        // 如果不支持权限检查，则直接尝试获取位置
        uni.getLocation({
          success: (res) => {
            that.map.latitude = parseFloat(res.latitude.toFixed(6));
            that.map.longitude = parseFloat(res.longitude.toFixed(6));
            console.log("获取地址", res);
          },
        });
      }
    // this.getList();
    this.isShow = queryParams.show;
    // console.log("queryParams1111", queryParams);
    if (this.isShow == 1 || this.isShow == "1") {
      if (queryParams.points == null) {
        return;
      }
      this.option = queryParams.points;
      this.area();
    } else {
      uni.showToast({
        title: "请按照地块边缘依次点击添加点",
        icon: "none",
      });
    }
  },
};
</script>

<style>
.map-polygon-root {
}
</style>
